package edu.xjtu.jih.forgetpwd;

import com.alibaba.fastjson.JSON;
import edu.xjtu.jih.common.Result;
import edu.xjtu.jih.common.Utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.Reader;

@WebServlet("/forgetpwd")
public class FopwdAPI extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        FopwdDto dto = null;

        try {
            req.setCharacterEncoding("UTF-8");

            Reader reader = req.getReader();
            CharArrayWriter out = new CharArrayWriter();//该输出流将数据输出到一个字符数组中

            try {
                char[] charBuff = new char[1024];
                int len = -1;//每次从输入流实际读取的字符数

                while ((len = reader.read(charBuff)) != -1) {
                    out.write(charBuff, 0, len);
                }
                out.flush();

                String json = out.toString();

                dto = JSON.parseObject(json, FopwdDto.class);

            } finally {
                out.close();
                reader.close();
            }

            FopwdService.updatepwd(dto);
            Utils.outResult(resp, Result.success());

        } catch (Exception e) {
            Utils.outResult(resp, Result.fail(Result.ERR_CODE_SYS, "马的，又一个异常，我ｃａｏ"));
        }
    }
}
